package com.hjy.cabinet.ws.service;

import android.util.Log;

import com.hjy.cabinet.db.BaseConfigInstance;
import com.hjy.cabinet.db.domain.BaseConfig;
import com.hjy.cabinet.ws.domain.ws.WbsocketResponseBody;
import com.hjy.cabinet.ws.domain.ws.WebSocketRequest;
import com.hjy.cabinet.ws.domain.ws.WsData;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
//fengqj
public class NetworkHander {
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    private static int count = 15;
    private BaseConfigInstance baseConfigInstance = BaseConfigInstance.getInstance();


    private static NetworkHander instance;

    private NetworkHander() {
    }


    public static NetworkHander getInstance() {
        if (instance == null) {
            synchronized (NetworkHander.class) {
                if (instance == null) {
                    instance = new NetworkHander();
                }
            }
        }
        return instance;
    }


    //心跳检测
    private void checkKA() {
//        reConnect(2);
        if (WsData.getKa()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            WbsocketResponseBody wbsocketResponseBody = kaRequest("Ka检测");
            if (!"success".equals(wbsocketResponseBody.getStatus())) {
                Log.d("心跳", "失败");
                WsData.webSocket = null;
                WsData.setKa(false);
                count = 15;
                connect();
            } else {
                Log.d("心跳", "成功");
                WsData.setKa(true);
                 WebsocketBasis websocketBasis = WebsocketBasis.getInstance();
                WsData.webSocket = websocketBasis.getWebSocket();
            }
        }
    }

    //断网重连

    public void connect() {

        while (WsData.webSocket == null && count > 0) {
            WebsocketBasis websocketBasis = WebsocketBasis.getInstance();
            websocketBasis.connectWebSocket(baseConfigInstance.getConfigByName("ip").getValue());
            WsData.webSocket = websocketBasis.getWebSocket();
            WbsocketResponseBody wbsocketResponseBody = kaRequest("连接");
            if ("success".equals(wbsocketResponseBody.getStatus())) {
                count=-1;
                Log.i("网络连接", "网络连接成功");
                WsData.setKa(true);
            }else {
                Log.i("网络连接", "网络连接失败");
                count--;
                WsData.webSocket = null;
                System.out.println("count"+count);
            }

        }

    }

    public void reConnect(int num) {

        if(count==0){
            count = num;
            connect();
        }


    }


    public void startScheduledLogSync() {

        scheduler.scheduleWithFixedDelay(this::checkKA, 0, 1, TimeUnit.SECONDS);
        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            System.err.println("Thread " + t.getName() + " threw exception: " + e);
        });
    }

    public WbsocketResponseBody kaRequest(String value1) {
        BaseConfig baseConfig = baseConfigInstance.getConfigByName("ip");
        String value = baseConfig.getValue();
        WebSocketRequest webSocketRequest = WebSocketRequest.create("KA", new Object[]{value1}, value);
        WebsocketService websocketService = WebsocketService.getInstance();
        WbsocketResponseBody wbsocketResponseBody = websocketService.sendMessageSynchronous(webSocketRequest, 1);
        return wbsocketResponseBody;
    }
}
